﻿using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace NazTek.Documenter.Ssis.Control.Tasks.PipeSubComponent
{
    internal sealed class OleDbDestination : Base
    {
        internal OleDbDestination(SsisPipe parent, IDTSComponentMetaData100 subComponent)
            : base(subComponent, parent)
        {
        }

        protected override Operation GetOperation(SsisPipe parent)
        {
            var statement = new StringBuilder(string.Format("INSERT INTO {0}<br>", GetTableName(Metadata)));
            var inputs = Metadata.InputCollection[0];
            var inCols = inputs.InputColumnCollection.Cast<IDTSInputColumn100>().ToArray();
            foreach (var outCol in inputs.ExternalMetadataColumnCollection.Cast<IDTSExternalMetadataColumn100>()
                .Where(col => inCols.Any(m => m.ExternalMetadataColumnID == col.ID)))
                statement.AppendFormat("\t{0} -> {1}<br>", inCols.First(i => i.ExternalMetadataColumnID == outCol.ID).Name,
                    outCol.Name);
            return new Operation
            {
                ConnectionName = parent.Parent.GetConnectionName(Metadata),
                Statement = statement.ToString()
            };
        }
    }
}